/*
 * Landmarks.java
 *
 * Created on April 16, 2007, 3:31 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.fpdev.core.basenet;

import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JFileChooser;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.fpdev.core.FPEngine;
import org.fpdev.core.basenet.Location;
import org.fpdev.core.basenet.LocationLandmark;
import org.fpdev.apps.rtemaster.gui.RMGUI;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author demory
 */
public class Landmarks {
  
  private FPEngine engine_;
  /** Creates a new instance of Landmarks */
  public Landmarks(FPEngine engine) {
    engine_ = engine;
  }
  
  public List<Location> resolveLandmarks(String input) {
    List<String> names = new ArrayList<String>();
    List<String> locStrs = new ArrayList<String>();
    
    List<Location> results = new LinkedList<Location>();
    
    try {
      ResultSet rs = engine_.getDB().queryLandmarks(input);
      while(rs.next()) {
        //String name = rs.getString(1);
        //String locStr = rs.getString(2);
        names.add(rs.getString(1));
        locStrs.add(rs.getString(2));
      }
      
      for(int i=0; i<names.size(); i++) {
        Location loc = engine_.getLocations().getResolvedNonLandmarkLocation(locStrs.get(i));
        results.add(new LocationLandmark(names.get(i), loc));
      }
      //rs.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
      
    return results;
  }
  
  public int landmarkCount() {
    return engine_.getDB().countRows("landmarks");
  }
  
  public void writeLandmarks(RMGUI gui) {

    JFileChooser chooser = new JFileChooser();
		String startDir = engine_.getProperty("5pHome")+"data"+File.separator+engine_.getDataPackage().getName()+File.separator+"route"+File.separator;
  	chooser.setCurrentDirectory(new File(startDir));
   	int returnVal = chooser.showOpenDialog(gui);
   	if(returnVal != JFileChooser.APPROVE_OPTION) return;
    
    engine_.getDB().createLandmarksTable();
    engine_.getDB().setActiveTable("landmarks");
    
		try {
			DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = docBuilder.parse(chooser.getSelectedFile());
			NodeList docNodes = doc.getChildNodes();
			Node thisNode = docNodes.item(0);
			if(docNodes.getLength() != 1 && !thisNode.getNodeName().equals("fivepoints")) {
				System.out.println("Not a valid Five Points datafile");
				return;
			}
			
			docNodes = thisNode.getChildNodes();
				
			for(int i=0; i<docNodes.getLength(); i++) {
				thisNode = docNodes.item(i);
				String name = thisNode.getNodeName();
				//System.out.println("xmlnode: "+thisNode.getNodeName());
				if(name.equals("landmarks")) {
					NodeList nodes = thisNode.getChildNodes();
					for(int ni=0; ni<nodes.getLength(); ni++) {
						Node lmNode = nodes.item(ni);
						if(lmNode.getNodeName().equals("lmaddr")) {
							NamedNodeMap attributes = lmNode.getAttributes();
							String lmName = attributes.getNamedItem("name").getNodeValue();
							String addr = attributes.getNamedItem("addr").getNodeValue();
              engine_.getDB().initLandmark(lmName, addr);
						}
						else if(lmNode.getNodeName().equals("lmnode")) {
							NamedNodeMap attributes = lmNode.getAttributes();
							String lmName = attributes.getNamedItem("name").getNodeValue();
							Integer nodeID = new Integer(attributes.getNamedItem("node").getNodeValue());
              engine_.getDB().initLandmark(lmName, "%"+nodeID+"%");
              
						}

						/*else if(lmNode.getNodeName()=="lmalias") {
							NamedNodeMap attributes = lmNode.getAttributes();
							String lmName = attributes.getNamedItem("name").getNodeValue();
							String target = attributes.getNamedItem("target").getNodeValue();
						}	*/					
					}
				}				
			}
      engine_.getDB().flushInsertOps();
		} catch(Exception e) {
			e.printStackTrace();
    }    
  }
  
  public void renameLandmark(String oldName, String newName) {
    
  }
  
  public void updateAltNames(String name, String altNames) {
    engine_.getDB().updateAttribute("landmarks", "name", name, "altnames", altNames);
  }

  public void updateLocation(String name, String locStr) {
  }
  
  public List<LandmarkInfo> getLandmarks() {
    List<LandmarkInfo> list = new LinkedList<LandmarkInfo>();
    ResultSet rs = engine_.getDB().getAllRows("landmarks");
    try {
      while(rs.next()) {
        list.add(new LandmarkInfo(rs.getString(1), rs.getString(2), rs.getString(3)));
      }
    } catch (SQLException ex) {
      ex.printStackTrace();
    }
    return list;
  }
  
  public class LandmarkInfo {
    public String name_, locStr_, altNames_;
    
    public LandmarkInfo(String name, String locStr, String altNames) {
      name_ = name;
      locStr_ = locStr;
      altNames_ = altNames;
    }
  }
}
